<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class SmsCode extends BaseModel
{
    protected $fillable = [
        'mobile', 'code', 'scene', 'ip', 'expire_time', 'is_validated'
    ];
    protected $table = 'sms_code';

    public $timestamps = false;

    const REGISTER = 1; // 注册
    const LOGIN = 2; // 登录
    const FORGET_PASSWORD = 3; // 忘记密码
    const MODIFY_PASSWORD = 4;// 修改密码
    const BIND_MOBILE = 5;// 绑定手机号
    const SUPPLIER_LOGIN = 6; // 供应商登录
    const SUPPLIER_REGISTER = 7; // 供应商注册
    const SUPPLIER_BIND_MOBILE = 8; // 供应商绑定手机号
    const SUPPLIER_MODIFY_MOBILE = 9; // 供应商修改手机
    const CHECK_MOBILE = 10; // 验证手机唯一性

    /**
     * 检查是否可以重复发送
     * @param Builder $query
     * @param int $second
     * @return Builder
     * @author john1668@qq.com
     */
    public function scopeByValid(Builder $query, int $second = 60): Builder
    {
        $now = time();
        $sub = $now - $second;

        return $query->whereBetween('expire_time', [$sub, $now]);
    }

    /**
     * 验证验证码
     * @param Builder $query
     * @param int $second
     * @return Builder
     * @author john1668@qq.com
     */
    public function scopeCheckValid(Builder $query, int $second = 600): Builder
    {
        $time = time();
        $now = $time - $second;

        return $query->where('status', 1)->where('over_time', '>', $now)->orderBy('id', 'desc');
    }

    //ip
    public function setIpAttribute($value)
    {
        $this->attributes['ip'] = sprintf("%u", ip2long($value));
    }

    /**
     * ip转换
     * @param $value
     * @return string
     */
    public function getIpAttribute($value)
    {
        return long2ip($value);
    }

}
